import { View, Text, Image, Input, RichText } from '@tarojs/components'
import {
	navigateTo,
	setNavigationBarTitle,
	showToast,
	showLoading,
	hideLoading,
	useDidHide,
	useUnload,
	setStorageSync,
} from '@tarojs/taro'
import { useState } from 'react'
import './index.scss'
import CloudIcons from '@/assets/ImageUrlConfig'
import SpacePage from './components/sapce/index'
import DrawerSpaceList from './components/drawer-space-list/index'
import DrawerArticleOperation from './components/drawer-article-operation/index'
import { useDispatch, useSelector } from 'react-redux'
import { AddSpaceApi } from '@/api/index'

export default function Index() {
	const dispatch = useDispatch()
	const userStore = useSelector((state) => state.user)
	const spaceStore = useSelector((state) => state.space)
	const articleStore = useSelector((state) => state.article)
	const recentStore = useSelector((state) => state.recent)

	useDidHide(() => {
		setStorageSync('current-using-space', spaceStore)
		setStorageSync('current-using-article', articleStore)
		setStorageSync('recent-read-article', recentStore)
	})

	/**
	 * 导航栏
	 */
	const [NavBarList] = useState([
		{ title: '空间', path: CloudIcons.list, static: false },
		{ title: '搜索', path: CloudIcons.search, pathName: 'search', static: false },
		{ title: '创作', path: CloudIcons.add, pathName: 'write', static: false },
		// { title: '通告', path: CloudIcons.notify, pathName: 'notify', static: true },
		{ title: '设置', path: CloudIcons.user, pathName: 'setting', static: true },
	])
	/**
	 * home组件默认class
	 */
	const Default_Container_Class_Name = 'home default' //'home space'
	/**
	 * home组件动态class
	 */
	const [homeCompClassName, sethomeConpClassName] = useState(Default_Container_Class_Name)

	/**
	 * 导航栏导航/去空间
	 * @param {*} item
	 * @returns
	 */
	const tapNavigateItem = (item) => {
		switch (item.title) {
			case '空间':
				goToSpace()
				break
			case '创作':
				navigateTo({
					url: `/pages/${item.pathName}/index?hello=fuck`,
				})
				break
			default:
				navigateTo({
					url: `/pages/${item.pathName}/index`,
				})
		}
	}
	/**
	 * 去空间页面
	 */
	const goToSpace = () => {
		if (userStore.space.length === 0) return
		if (homeCompClassName === Default_Container_Class_Name) {
			sethomeConpClassName('home space')
			setNavigationBarTitle({ title: '空间' })
		} else {
			sethomeConpClassName('home default')
			setNavigationBarTitle({ title: '首页' })
		}
	}
	/**
	 * 是否展示输入框，以填写空间名字
	 */
	const [isShowInputPopoverForFullSpaceName, setIsShowInputPopoverForFullSpaceName] = useState(false)
	/**
	 * 创建一个空间
	 */
	const createNewSpace = (e) => {
		setIsShowInputPopoverForFullSpaceName(false)
		const spaceName = e.detail.value

		showLoading({ title: '创建中' })

		AddSpaceApi({ name: spaceName })
			.then((data) => {
				showToast({
					title: '创建成功',
					icon: 'success',
					duration: 1000,
				})
				const { user, space } = data
				dispatch({
					type: 'UPDATE_USER',
					payload: user,
				})
				dispatch({
					type: 'UPDATE_SPACE',
					payload: space,
				})
			})
			.catch((err) => {
				showToast({
					title: '创建失败',
					icon: 'error',
					duration: 1000,
				})
				throw err
			})
			.finally(() => {
				hideLoading()
			})
	}

	const [isShowSpaceListDrawer, setIsShowSpaceListDrawer] = useState(false)
	const showSpaceListDrawer = () => {
		setIsShowSpaceListDrawer(true)
	}

	const [isShowArticleOperationDrawer, setIsShowArticleOperationDrawer] = useState(false)
	const [currentActiveArticleID, setCurrentActiveArticleID] = useState('')
	const showArticleOperationDrawer = (articleid) => {
		setIsShowArticleOperationDrawer(true)
		setCurrentActiveArticleID(articleid)
	}

	return (
		<View className='index'>
			<SpacePage
				sethomeConpClassName={sethomeConpClassName}
				showSpaceListDrawer={showSpaceListDrawer}
				showArticleOperationDrawer={showArticleOperationDrawer}
			></SpacePage>

			<View className={homeCompClassName}>
				{/* 左侧空间列表 */}
				{userStore.space?.length ? null : (
					<View
						className='empty-warn'
						onTap={() => {
							setIsShowInputPopoverForFullSpaceName(true)
						}}
					>
						<Image className='image' src={CloudIcons.empty}></Image>
						<Text className='text'>您还没有写作过,请先创建一个空间</Text>
					</View>
				)}
				{/* 预览区域 */}
				{articleStore?.content ? <RichText className='richtext' nodes={articleStore.content}></RichText> : null}
				{/* 导航栏 */}
				<View className='navgation-bar default'>
					{NavBarList.map((tab, index) => {
						return tab.static || userStore.space?.length ? (
							<View
								className='item-warp'
								onTap={() => {
									tapNavigateItem(tab)
								}}
							>
								<Image className='item' src={tab.path} key={index}></Image>
							</View>
						) : null
					})}
				</View>
			</View>

			{/* 弹窗 - 输入空间名字 */}
			{isShowInputPopoverForFullSpaceName ? (
				<View
					className='mask'
					onTap={() => {
						setIsShowInputPopoverForFullSpaceName(false)
					}}
				>
					<View
						className='popover'
						onTap={(e) => {
							e.stopPropagation()
						}}
					>
						<Input className='input' onConfirm={createNewSpace} focus placeholder='请为新空间起一个名字'></Input>
					</View>
				</View>
			) : null}

			{/* 抽屉 - 切换current using sapce */}
			<DrawerSpaceList
				show={isShowSpaceListDrawer}
				setShow={setIsShowSpaceListDrawer}
				setIsShowInputPopoverForFullSpaceName={setIsShowInputPopoverForFullSpaceName}
			></DrawerSpaceList>
			{/* 抽屉 - 操作文章（删除，移动...） */}
			<DrawerArticleOperation
				currentActiveArticleID={currentActiveArticleID}
				show={isShowArticleOperationDrawer}
				setShow={setIsShowArticleOperationDrawer}
			></DrawerArticleOperation>
		</View>
	)
}
